package com.lzw.bluetoothpractice.Fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.airsaid.pickerviewlibrary.OptionsPickerView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.android.material.tabs.TabLayout;
import com.lzw.bluetoothpractice.Activitys.HealthyDetailActivity;
import com.lzw.bluetoothpractice.Adapters.RecoveryActionListAdapter;
import com.lzw.bluetoothpractice.AppConfig;
import com.lzw.bluetoothpractice.Models.Temperature;
import com.lzw.bluetoothpractice.Models.Walk;
import com.lzw.bluetoothpractice.MyApplication;
import com.lzw.bluetoothpractice.R;
import com.lzw.bluetoothpractice.Utils.AppUtil;
import com.lzw.bluetoothpractice.Utils.SharePreferenceUtils;
import com.lzw.bluetoothpractice.Utils.TimeUtils;
import com.lzw.bluetoothpractice.bean.HealthyMessageBean;
import com.lzw.bluetoothpractice.network.HeadAssmblyUtils;
import com.lzw.bluetoothpractice.network.RetrofitManager;
import com.lzw.bluetoothpractice.network.api.RequestApi;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.lzw.bluetoothpractice.MyApplication.getContext;

public class StepRecordFragment extends Fragment {
    private Map<String, String> keyMap;
    View view;
    Context mcontext;
    TextView tvTime;
    Button btStart;
    Button btEnd;
    TextView distance;
    TextView energy;
    TextView speed;
    TextView step;
    ImageView iconBack;
    TextView tvtitle;
    ImageView iconSet;
    private boolean isStopCount = false;
    private int currentSecond = 0;//当前毫秒数
    private int startStep=0;
    private int endStep;
    private boolean isPause = false;

    String deviceId;
    private Handler mHander=new Handler();
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
         view = inflater.inflate(R.layout.activity_step_record,null);
        // Toast.makeText(getActivity(),"Message发布成功啦！", Toast.LENGTH_SHORT).show();
        deviceId = SharePreferenceUtils.getString(getContext(),"DeviceId",null);
        iconBack=(ImageView)view.findViewById(R.id.navBack);
        iconSet=(ImageView)view.findViewById(R.id.navSet);
        tvtitle=view.findViewById(R.id.tvTitle);
        startStep= Integer.parseInt(MyApplication.getInstance().step);
        InitView();

        return view;
    }
    public void InitView(){
        distance=view.findViewById(R.id.distance);
        energy=view.findViewById(R.id.energy);
        speed=view.findViewById(R.id.speed);
        step=view.findViewById(R.id.step);
        tvTime=view.findViewById(R.id.tvTime);
        btStart=view.findViewById(R.id.btStart);
        btEnd=view.findViewById(R.id.btEnd);
        btStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isPause){
                    btStart.setText("暂停");

                    mHander.post(timeRunable);
                }else{
                    btStart.setText("开始");

                    mHander.removeCallbacks(timeRunable);
                }
                isPause=!isPause;


            }
        });
        btEnd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(currentSecond==0){
                    return;
                }

                btStart.setText("开始");
                isPause=false;
                endStep=Integer.parseInt(MyApplication.getInstance().step);
                if (endStep-startStep==0){
                    distance.setText("0");
                    step.setText("0");
                    energy.setText("0");
                    speed.setText("0");
                }else {
                    distance.setText(""+(endStep-startStep)*0.5);
                    step.setText(""+(endStep-startStep));
                    energy.setText(""+(endStep-startStep)*0.04);
                    //Log.e("速度",""+currentSecond);
                    if (currentSecond!=0){
                        speed.setText(""+(Double.parseDouble(endStep-startStep+"")*1000)/currentSecond);
                    }else {
                        speed.setText("0");
                    }


                }
               String userid = SharePreferenceUtils.getString(getContext(),"userId",null);
                Walk walk=new Walk();
                walk.setDeviceId(Long.parseLong(deviceId));
                walk.setDistance(BigDecimal.valueOf((endStep-startStep)*0.5));
                walk.setSpeed((Double.parseDouble(endStep-startStep+"")*1000)/currentSecond);
                walk.setUserId(Long.parseLong(userid));
                walk.setWalk(Long.parseLong(endStep-startStep+""));

                try {
                    keyMap = HeadAssmblyUtils.HeadAssembly("/dev-api/android/message/messageId");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                String accessToken = SharePreferenceUtils.getString(getContext(),"access_token",null);;
                RetrofitManager.getInstance(AppConfig.BASE_URL)
                        .createReq(RequestApi.class).addWalk(walk,"*:*:*","1", AppUtil.getVersionCode() + "", accessToken, keyMap.get("gmtStr"), keyMap.get("contentMD5"), keyMap.get("hmacCode")).
                        observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                        Log.e("增加行走记录",e.getMessage()+"");

                    }

                    @Override
                    public void onNext(JSONObject json) {



                        if(json.getInteger("code")==200){

                            Toast toast=Toast.makeText(getContext(),"记录数据成功",Toast.LENGTH_LONG);
                            toast.show();


                        }else {
                            Toast toast=Toast.makeText(getContext(),"记录数据失败",Toast.LENGTH_LONG);
                            toast.show();
                        }


                    }
                });

                Temperature temperature=new Temperature();
                temperature.setUserId(Long.parseLong(userid));
                temperature.setDeviceId(Long.parseLong(deviceId));
                temperature.setTemperature(Double.parseDouble(MyApplication.getInstance().temperature));
                RetrofitManager.getInstance(AppConfig.BASE_URL)
                        .createReq(RequestApi.class).addTemp(temperature,"*:*:*","1", AppUtil.getVersionCode() + "", accessToken, keyMap.get("gmtStr"), keyMap.get("contentMD5"), keyMap.get("hmacCode")).
                        observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                        Log.e("增加温度记录",e.getMessage()+"");

                    }

                    @Override
                    public void onNext(JSONObject json) {



                        if(json.getInteger("code")==200){

                            Toast toast=Toast.makeText(getContext(),"记录数据成功",Toast.LENGTH_LONG);
                            toast.show();


                        }else {
                            Toast toast=Toast.makeText(getContext(),"记录数据失败",Toast.LENGTH_LONG);
                            toast.show();
                        }


                    }
                });
                currentSecond = 0;
                mHander.removeCallbacks(timeRunable);
            }
        });

    }
    protected void InitNavBar(boolean isShowBack,String title,boolean isShowSet){
        iconBack.setVisibility(isShowBack ? View.VISIBLE : View.GONE);
        iconSet.setVisibility(isShowSet ? View.VISIBLE : View.GONE);
        tvtitle.setText(title);
    }

    private Runnable timeRunable = new Runnable() {
        @Override
        public void run() {

            currentSecond = currentSecond + 1000;
            endStep=Integer.parseInt(MyApplication.getInstance().step);
            if (endStep-startStep==0){
                distance.setText("0");
                step.setText("0");
                energy.setText("0");
                speed.setText("0");

            }else {
                distance.setText(""+(endStep-startStep)*0.5);
                step.setText(""+(endStep-startStep));
                energy.setText(""+(endStep-startStep)*0.04);
                // Log.e("速度",""+currentSecond);
                speed.setText(""+((endStep-startStep)*50000)/currentSecond);

            }
            tvTime.setText(TimeUtils.getFormatHMS(currentSecond));
            //递归调用本runable对象，实现每隔一秒一次执行任务
            mHander.postDelayed(this, 1000);

        }

    };
}
